package com.vae.canal.listener;

import com.alibaba.fastjson.JSON;

import com.vae.mall.goods.api.entity.Spu;

import com.vae.search.feign.SpuSearchFeign;

import com.vae.search.model.SpuEs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * spu表监听器，当数据发生改变的时候同步更新es
 */
@CanalTable(value = "spu")
@Component
public class SpuHandler implements EntryHandler<Spu> {
    @Autowired
    private SpuSearchFeign spuSearchFeign;


    /***
     * 增加spu
     * @param spu
     */
    @Override
    public void insert(Spu spu) {
        //当spu的状态为：已经审核，未删除，已上架时添加到索引库
        if(spu.getStatus().intValue()==1
        &&spu.getIsDelete().intValue()==0&&spu.getIsMarketable().intValue()==1){
            //导入索引
            // 将spu转为JSON，再讲JSON转为spuEs

            spuSearchFeign.add(JSON.parseObject(JSON.toJSONString(spu), SpuEs.class));
        }
    }

    /***
     * 修改spu
     * @param before
     * @param after
     */
    @Override
    public void update(Spu before, Spu after) {
        if(after.getStatus().intValue()==0||after.getStatus().intValue()==2||
        after.getIsDelete().intValue()==1||after.getIsMarketable().intValue()==0){
            // 如果spu下架,删除,未审核，审核不通过，删除索引
            spuSearchFeign.del(after.getId());
        }else{
            // 更新
            spuSearchFeign.add(JSON.parseObject(JSON.toJSONString(after), SpuEs.class));
        }
    }

    /***
     *删除spu
     * @param spu
     */
    @Override
    public void delete(Spu spu) {
        spuSearchFeign.del(spu.getId());
    }
}
